package com.ji.TestZookeeper.curator.sharedlock;

import java.util.List;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessReadWriteLock;
import org.apache.curator.utils.CloseableUtils;

import com.google.common.collect.Lists;
import com.ji.TestZookeeper.curator.ClientFactory;

public class DistributedLockMain {
	private static CuratorFramework client = ClientFactory.newClient();
	// private static CuratorFramework client2 = ClientFactory.newClient2();
	private static final String PATH = "/locks";

	// 进程内部（可重入）读写锁
	private static final InterProcessReadWriteLock lock;
	// 进程内部（可重入）读写锁
	// private static final InterProcessReadWriteLock lock2;
	// 读锁
	private static final InterProcessLock readLock;
	// 写锁
	private static final InterProcessLock writeLock;
	// 写锁
	// private static final InterProcessLock writeLock2;

	static {
		client.start();
		// client2.start();
		lock = new InterProcessReadWriteLock(client, PATH);
		readLock = lock.readLock();
		writeLock = lock.writeLock();
		// lock2 = new InterProcessReadWriteLock(client2, PATH);
		// writeLock2 = lock2.writeLock();
	}

	public static void main(String[] args) {
		try {
			List<Thread> jobs = Lists.newArrayList();
			// 读线程
			for (int i = 0; i < 10; i++) {
				Thread t = new Thread(new ParallelJob("Parallel任务" + i, readLock));
				jobs.add(t);
			}
			// 写线程
			for (int i = 0; i < 10; i++) {
				Thread t = new Thread(new MutexJob("Mutex任务" + i, writeLock));
				jobs.add(t);
			}

			for (Thread t : jobs) {
				t.start();
			}
			Thread.sleep(100000000);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			CloseableUtils.closeQuietly(client);
		}
	}
}